<template>
  <div class="index">
    <NavBar/>
    <div class="container" v-if="infoData">
      <div class="item plan-tk-t">
        <div class="photo-tk-t-l">
          <div class="photo"><img :src="infoData.user.avatar"></div>
          <template v-if="infoData.plan.userId !== userId">
            <button v-if="infoData.opinionLeader.isMyFocus === '0'" class="followed" @click="focus()" @mouseout="followHoverFlag = false" @mouseover="followHoverFlag = true">
              {{followHoverFlag ? '取消关注':'已关注'}}
            </button>
            <button v-else @click="focus()">+关注</button>
          </template>
        </div>
        <div class="plan-intro">
          <h1 class="ftz16">{{infoData.plan.name}}</h1>
          <p>
            <label>简介：</label>
            <i id="intro">{{newIntro}}</i>
            <a v-if="infoData.plan.intro.length > 52" href="javascript:void(0)" @click="showAllIntroFlag=!showAllIntroFlag" id="fold">
              {{showAllIntroFlag ? '收起↑': '展开↓'}}
            </a>
          </p>
          <p>
            <label>能力圈：</label>{{infoData.plan.abilityCircle}}</p>
          <p>
            <label>服务期限：</label>{{infoData.plan.beginTime | parseTime('{y}-{m}-{d}')}} 至 {{infoData.plan.endTime | parseTime('{y}-{m}-{d}')}} </p>
          <p>
            <label>更新频率：</label>{{infoData.plan.updateFrequency}}</p>
        </div>
        <div class="plan-tk-t-r">
          <span>
            <i>{{infoData.plan.saleNum}}</i>人订阅</span>
          <p>
            <i>
              <span class="icon-coin"></span>{{parseFloat(infoData.plan.price)}}</i>
          </p>
          <p>
            <!-- 在售 -->
            <template v-if="infoData.plan.saleFlag === 1">
              <template v-if="infoData.plan.userId !== userId">
                <button id="sub_btn" v-if="!infoData.paid" @click="execSubscribe">我要订阅</button>
                <button id="sub_btn" class="on" v-else @mouseout="showCancleSubBtn = false" @mouseover="showCancleSubBtn = true" @click="execSubscribe">
                  {{showCancleSubBtn ? '取消订阅' : '已订阅'}}
                </button>
              </template>
            </template>
            <!-- 停售 -->
            <template v-else>
              <button id="sub_btn" class="on">
                已停售
              </button>
            </template>
          </p>
        </div>
      </div>
      <div class="plan-tk-c w73">
        <div class="item">
          <template v-if="infoData.articles.list.length > 0">
            <div class="plan-box">
              <!-- <div class="plan-box" v-for="(tempItem, index) in infoData.articles.list" :key="index"> -->
              <template v-for="(item, index) in infoData.articles.list">
                <router-link v-if="isAdd(index, item.articleId)" tag="a" class="plan-item" :key="item.articleId" :to="'/planarticle/' + item.articleId">
                  <!-- <span v-if="index == 0" class="date new ftz16">{{item.createTime | parseTime('{m}-{d} 星期{a}')}}</span> -->
                  <span class="date new ftz16">{{item.createTime | parseTime('{m}-{d} 星期{a}')}}</span>
                  <a href="" class="photo">
                    <img :src="item.imgUrl">
                  </a>
                  <div class="fr info">
                    <div href="" class="title">
                      <label :class="tagClassFilter(item.tagText)">{{item.tagText }}</label>
                      <b class="ftz16">{{item.title}}</b>
                    </div>
                    <div class="txt" txt>
                      <span>{{item.summary}}</span>
                      <a href="">【查看】</a>
                    </div>
                    <div class="tips">
                      <span>{{item.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
                      <span class="line"></span>
                      <span> {{item.planSaleNum ? item.planSaleNum: '0'}}人解锁</span>
                      <a class="fr lock" href="javascript:void(0)">
                        <template v-if="item.tagText==='试读'">
                          <span>
                            试读
                          </span>
                        </template>
                        <template v-else>
                          <span v-if="infoData.paid === 1 || infoData.plan.userId === userId">
                            <i class="icon icon-locked"></i>已解锁
                          </span>
                          <span v-else>
                            <i class="icon"></i>解锁全文
                          </span>
                        </template>
                      </a>
                    </div>
                  </div>
                </router-link>
              </template>
            </div>
          </template>
          <NoDataTips v-else/>
        </div>
        <button v-if="infoData.articles.total > infoData.articles.list.length" class="load-more ftz16" @click="loadMore">
          <template v-if="isLoadingMore">
            <i class='layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop ftz20'></i>
            <span>正在加载，请稍候......</span>
          </template>
          <span v-else>点击加载更多...</span>
        </button>

      </div>
      <div class="plan-r w23 fr">
        <!-- 计划试读 -->
        <LeftPanelPtry :list="previewTryList" :authorId="authorId" />
        <LeftPanelViewpoint :list="viewPointList" :authorId="authorId" />
        <LeftPanelLive :list="liveList" :authorId="authorId" />
      </div>
      <EvaluatingBox :showFlag="showEvaluatingBoxFlag" @closeFn="ctrlEvaluatingBox" />
    </div>
    <Footer/>
  </div>
</template>

<script>
import NavBar from '@/components/nav-bar'
import Footer from '@/components/footer'
import LeftPanelViewpoint from '@/components/plan/left-panel-viewpoint'
import LeftPanelPtry from '@/components/plan/left-panel-ptry'
import LeftPanelLive from '@/components/plan/left-panel-live'
import EvaluatingBox from '@/components/plan/evaluating-box'
import {
  getPlanDetailInfo,
  getPlanTopArticle,
  getPlanFreeArticle,
  getPlanArticleList,
  modifyUserFocus,
  cancelSubscribePlan,
  getArticleByStatus, // 获取观点
  getMyLive // 获取直播
} from '@/service/api'
import { mapState } from 'vuex'
export default {
  components: {
    NavBar,
    Footer,
    LeftPanelViewpoint,
    LeftPanelPtry,
    LeftPanelLive,
    EvaluatingBox
  },
  mounted () {
    this.$nextTick(() => {
      // this.id = this.$route.params.id
      this.searchData.planId = this.id
      if (window.layer) {
        this.layerLoad = window.layer.load(0, {
          shade: false
        })
      }
      this.initData()
    })
  },
  computed: {
    newIntro: {
      get () {
        if (this.showAllIntroFlag) {
          return this.infoData.plan.intro
        } else {
          return this.infoData.plan.intro.substring(0, 51)
        }
      }
    },
    id () {
      return this.$route.params.id
    },
    // ...mapGetters([
    //   'me'
    // ]),
    ...mapState({
      me: state => state.me || {}
    }),
    userId () {
      return this.$store.state.me.sysUser.userId
    }
  },
  watch: {
    id (val) {
      console.log(val)
      this.searchData.planId = val
      this.initData()
      // this.$router.push({
      //   name: 'plan',
      //   params: {
      //     id: val
      //   }
      // })
      return val
    }
  },
  data () {
    return {
      // id: 0,
      authorId: '',
      showAllIntroFlag: false,
      showCancleSubBtn: false, // 是否显示取消订阅按钮。hover事件使用
      showEvaluatingBoxFlag: false, // 是否显示评测提示窗口
      infoData: null,
      topArticleId: '',
      viewPointList: [],
      previewTryList: [],
      liveList: [],
      isLoadingMore: false, // 加载更多
      searchData: {
        planId: '',
        pageSize: 6,
        pageNum: 1
      },
      layerLoad: null,
      followHoverFlag: false // 关注按钮是否hover
    }
  },
  methods: {
    /**
     * 初始化页面数据，多个ajax同时请求
     */
    initData () {
      Promise.all([
        this.getFreeArticle(),
        this.getDetailInfo(),
        this.getTopArticle()
      ]).then((res) => {
        // 试读
        let freeData = res[0]
        if (freeData.status === 200) {
          if (freeData.data && freeData.data.data) {
            this.previewTryList = freeData.data.data.list
          }
        } else {
          this.errorMsg('获取试读计划失败')
        }
        // 计划详情
        let detailData = res[1]
        if (detailData.status === 200) {
          let tempDetailData = detailData.data
          if (tempDetailData.data) {
            this.infoData = tempDetailData.data
          }
        } else {
          this.errorMsg('获取计划详情失败')
        }
        // 置顶文章
        let topArticleData = res[2]
        if (topArticleData.status === 200) {
          let tempData = topArticleData.data
          if (tempData.data) {
            this.topArticleId = tempData.data.articleId
            this.infoData.articles.list.unshift(tempData.data)
          }
        } else {
          this.errorMsg('获取置顶文章失败')
        }
        this.authorId = this.infoData.user.userId // 作者id
        // 他的观点
        this.getViewPointList()
        // 他的直播
        this.getLiveThemeList()
        window.layer.close(this.layerLoad)
      }).catch((e) => {
        console.log(e)
      })
    },
    // 计划详情
    async getDetailInfo () {
      let res = await getPlanDetailInfo(this.searchData)
      return res
    },
    // 置顶文章
    async getTopArticle () {
      let res = await getPlanTopArticle({ planId: this.id })
      return res
    },
    // 试读文章
    async getFreeArticle () {
      let res = await getPlanFreeArticle({ planId: this.id })
      return res
    },
    // 文章分页列表
    async getArticleList () {
      let res = await getPlanArticleList(this.searchData)
      return res
    },
    // 获取他的观点
    async getViewPointList () {
      let searchInfo = {
        userId: this.authorId,
        pageSize: 6,
        pageNum: 1
      }
      await getArticleByStatus(searchInfo).then(res => {
        if (res.status === 200) {
          let tempData = res.data
          if (tempData.data) {
            this.viewPointList = tempData.data.list
          }
        } else {
          this.errorMsg('获取他的直播列表失败')
        }
      })
    },
    // 获取他的直播主题列表
    async getLiveThemeList () {
      let searchInfo = {
        userId: this.authorId,
        pageSize: 6,
        pageNum: 1
      }
      await getMyLive(searchInfo).then(res => {
        if (res.status === 200) {
          let tempData = res.data
          this.liveList = tempData.list
        } else {
          this.errorMsg('获取他的直播列表失败')
        }
      })
    },
    // 取消订阅
    async doCancelSubscribePlan () {
      let res = await cancelSubscribePlan({ planId: this.id })
      return res
    },
    tagClassFilter (tag) {
      let index = ['置顶', '火热', '试读', '重磅'].indexOf(tag)
      return ['lb1', 'lb2', 'lb3', 'lb4'][index]
    },
    async focus () {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再关注！')
        return false
      }
      let flag = this.infoData.opinionLeader.isMyFocus === '0' ? '1' : '0'
      await modifyUserFocus({
        focusUserId: this.infoData.opinionLeader.userId,
        focusStatus: flag
      })
      this.infoData.opinionLeader.isMyFocus = flag
    },
    /**
     * 下单购买计划
     * this.infoData.paid === 1  // 已购买 0
     * this.infoData.paid === 0  // 未购买
     */
    execSubscribe () {
      if (!this.userId) {
        window.layui.layer.msg(`请登录后再订阅！`)
        return false
      }
      // 自己发布的计划，应跳转计划详情页
      if (this.infoData.plan.userId === this.me.sysUser.userId) {
        window.layui.layer.msg('您为该计划作者，无需订阅')
      } else {
        if (!this.infoData.paid) {
          if (!this.me.riskTest) {
            this.ctrlEvaluatingBox()
            return
          }
          this.$router.push('/plan/pay/' + this.infoData.plan.planId)
        } else {
          // 取消订阅
          this.cancelSubscribe()
        }
      }
    },
    cancelSubscribe () {
      let that = this
      window.layer.open({
        type: 1,
        offset: 'auto',
        id: 'layerDemo' + 'auto', // 防止重复弹出
        content: '<div style="padding: 20px 100px;">取消后您将无法查看计划文章，确认取消订阅吗？</div>',
        btn: '确认',
        btnAlign: 'c',
        shade: 0,
        yes: function () {
          that.doCancelSubscribePlan().then((res) => {
            if (res.data && res.data.code === 200) {
              that.infoData.paid = 0
            }
            if (window.layer) {
              window.layer.closeAll()
            }
          })
        }
      })
    },
    ctrlEvaluatingBox () {
      this.showEvaluatingBoxFlag = !this.showEvaluatingBoxFlag
    },
    loadMore () {
      this.isLoadingMore = true
      this.searchData.pageNum++
      this.getArticleList().then((res) => {
        if (res.status === 200) {
          let tempDetailData = res.data
          if (tempDetailData.data) {
            this.infoData.articles.list.push(...tempDetailData.data.list)
          } else {
            this.searchData.pageNum--
            this.errorMsg()
          }
        } else {
          this.searchData.pageNum--
          this.errorMsg()
        }
      })
      this.isLoadingMore = false
    },
    /**
     * 是否添加，为了从list列表中过滤掉置顶文章
     */
    isAdd (index, articleId) {
      if (index === 0) {
        return true
      }
      if (articleId === this.topArticleId) {
        return false
      }
      return true
    },
    errorMsg (name) {
      window.layui.layer.msg(name + '数据加载失败，请重新加载')
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  min-height: auto;
}
.plan-tk-t {
  overflow: hidden;
  background-image: url("../../assets/res/img/plan_info_bg.png");
  background-repeat: no-repeat;
  margin: 30px 0;
}
.plan-tk-t .photo-tk-t-l {
  width: 140px;
  display: inline-block;
  vertical-align: top;
  margin: 16px 0;
}
.plan-tk-t .photo-tk-t-l .photo {
  width: 94px;
  height: 94px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 auto;
}
.plan-tk-t .photo-tk-t-l .photo img {
  width: 100%;
  height: 100%;
}
.plan-tk-t .photo-tk-t-l button {
  display: block;
  width: 70px;
  height: 28px;
  color: #fff;
  border-radius: 14px;
  background: #e94f4f;
  font-size: 12px;
  margin: 8px auto;
  &.followed {
    background-color: #a6a6a6;
  }
}
.plan-tk-t .plan-intro {
  width: 810px;
  color: #fff;
  display: inline-block;
  vertical-align: top;
  margin: 16px 0 25px 0;
}
.plan-tk-t .plan-intro h1 {
  font-weight: bold;
}
.plan-tk-t .plan-intro p {
  display: block;
  margin-top: 8px;
  padding-left: 14px;
  line-height: 22px;
}
.plan-tk-t .plan-intro p label {
  padding-left: 6px;
  border-left: 3px solid #e94f4f;
  display: inline-block;
  height: 14px;
  line-height: 14px;
  margin-left: -14px;
}
.plan-tk-t .plan-intro p a {
  color: #26baeb;
  margin-left: 4px;
}
.plan-tk-t .plan-tk-t-r {
  display: inline-block;
  vertical-align: top;
  width: 210px;
  text-align: center;
  margin: 47px 0;
}
.plan-tk-t .plan-tk-t-r p {
  margin-top: 8px;
}
.plan-tk-t .plan-tk-t-r span i {
  margin-right: 4px;
}
.plan-tk-t .plan-tk-t-r p i {
  color: #e94f4f;
  font-weight: bold;
}
.plan-tk-t .plan-tk-t-r p button {
  width: 90px;
  color: #fff;
  height: 30px;
  background: #e94f4f;
  border-radius: 15px;
  font-size: 12px;
}
.plan-tk-t .plan-tk-t-r p .on {
  background: #a6a6a6;
}
.plan-tk-c {
  display: inline-block;
  vertical-align: top;
}
.plan-tk-c .plan-box {
  padding: 30px 16px 0 16px;
}
.plan-tk-c .plan-box .plan-item {
  display: block;
  position: relative;
  padding: 24px 0;
  border-top: 1px solid #e6e6e6;
}
.plan-tk-c .plan-box .plan-item .date {
  height: 14px;
  line-height: 14px;
  position: absolute;
  left: 0;
  top: -8px;
  font-weight: bold;
  background: #fff;
  padding: 0 8px;
  border-left: 3px solid #b2b2b2;
}
.plan-tk-c .plan-box .plan-item .new {
  border-left: 3px solid #e94f4f;
}
.plan-tk-c .photo {
  display: inline-block;
  vertical-align: top;
  width: 140px;
  height: 100px;
  overflow: hidden;
}
.plan-tk-c .photo img {
  width: 100%;
  height: 100%;
}
.plan-tk-c .info {
  width: 670px;
  height: 100px;
  display: inline-block;
  vertical-align: top;
  margin-right: 16px;
  position: relative;
}
.plan-tk-c .info .title {
  display: block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.plan-tk-c .info .title label {
  font-size: 12px;
  height: 22px;
  line-height: 20px;
  display: inline-block;
  vertical-align: middle;
  border-radius: 5px;
  color: #fff;
  padding: 0 7px;
  margin-right: 10px;
  margin-top: -4px;
}
.plan-tk-c .info .title .lb1 {
  background: #00a0e9;
}
.plan-tk-c .info .title .lb2 {
  background: #e94f4f;
}
.plan-tk-c .info .title .lb3 {
  background: #ff8f16;
}
.plan-tk-c .info .title .lb4 {
  background: #b659fd;
}
.plan-tk-c .info .txt {
  color: #808080;
  line-height: 22px;
  margin-top: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -moz-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 42px;
}
.plan-tk-c .info .txt a {
  color: #248cda;
}
.plan-tk-c .info .tips {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  color: #808080;
}
.plan-tk-c .info .tips .line {
  display: inline-block;
  vertical-align: middle;
  height: 14px;
  width: 1px;
  background: #cccccc;
  margin: -4px 10px 0 10px;
}
.plan-tk-c .info .tips .lock {
  color: #ff6325;
}
.plan-tk-c .info .tips .lock .icon {
  display: inline-block;
  vertical-align: middle;
  width: 18px;
  height: 18px;
  background-image: url("../../assets/res/img/icon.png");
  background-repeat: no-repeat;
  background-position: -22px -164px;
  margin-right: 8px;
}
.plan-tk-c .info .tips .lock .icon-locked {
  background-position: -56px -164px;
}
.plan-tk-c .load-more {
  display: block;
  width: 100%;
  height: 38px;
  background: #fff;
  color: #808080;
  border: 1px solid #e5e5e5;
  border-radius: 5px;
  margin-top: 20px;
}
.plan-r .item {
  margin-bottom: 30px;
}
</style>
